const request = require("request");
const fs = require('fs')
const url = require("url");
const querystring = require("querystring");

// 测试url: https://view.csslcloud.net/api/view/assistant?roomid=F4F059CEBD50BB899C33DC5901307461&userid=44CACEB725BAB224

let allNames = [];
fs.readFile("names.txt", "utf-8", (err, data) => {
    if (err) return console.log("读取名单失败！")
    allNames = data.toString().trim().split("\r\n")
    // console.log("所有学员名单")
    // console.log(allNames)
})

if (!process.argv[2]) {
    return console.log("请输入讲师或助教端直播地址!")
}

let address = process.argv[2]
let reg = new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/);
if (!reg.test(address)) return console.log("请输入合法的url地址")

var arg = url.parse(address).query;
//将arg参数字符串反序列化为一个对象
var params = querystring.parse(arg);

if (!params.userid || !params.roomid) {
    return console.log("请输入合法的url地址")
}

request({
    url: "https://view.csslcloud.net/api/inline/room/onlineusers?&userid=" + params.userid + "&roomid=" + params.roomid + "&value=&type=2",//请求路径
    method: "GET",//请求方式，默认为get
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body)
        let onlineUsers = JSON.parse(body).onlineUsers
        // console.log(onlineUsers)
        if (onlineUsers) {
            let onlineStudents = onlineUsers.filter(item => {
                return item.role == "student"
            })

            // console.log(onlineStudents)
            let onlineNames = onlineStudents.map(item => {
                return item.name
            })

            // console.log("在线学员名单")
            // console.log(onlineNames)

            let offlineNames = allNames.filter(item => {

                return onlineNames.indexOf(item) === -1
            })

            console.log("学生总数: " + allNames.length + "\n")

            console.log("在线学生数量: " + onlineStudents.length + "\n")

            console.log("班级出勤率: " + (onlineStudents.length * 100 / allNames.length + "%") + "\n")

            console.log("在线老师数量: " + (onlineUsers.length - onlineStudents.length) + "\n")

            console.log("缺勤数量: " + offlineNames.length + "\n")

            console.log("缺勤学生: " + offlineNames.join(" "))
        }
    } else {
        console.log("网络异常")
    }
})